package com.thinvent.remotepassword.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thinvent.remotepassword.dto.IppasswordDTO;
import com.thinvent.remotepassword.entity.Ippassword;
import com.thinvent.remotepassword.service.IppasswordService;
import com.thinvent.remotepassword.util.DataConvertUtils;
import com.thinvent.remotepassword.util.RequestUtil;
import com.thinvent.remotepassword.vo.HostDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;

/**
 * (Ippassword)表控制层
 *
 * @author makejava
 * @since 2024-06-06 16:46:19
 */
@RestController
@RequestMapping("ippassword")
public class IppasswordController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private IppasswordService ippasswordService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param ippassword 查询实体
     * @return 所有数据
     */
    @GetMapping("/selectAll")
    public R selectAll(Page<Ippassword> page, Ippassword ippassword) {
        return success(this.ippasswordService.page(page, new QueryWrapper<>(ippassword)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.ippasswordService.getById(id));
    }
    @GetMapping("/selectOne")
    public R selectOne(@RequestBody IppasswordDTO ippasswordDTO, HttpServletRequest request) {
        Ippassword ippassword = DataConvertUtils.convertDO2DTO(ippasswordDTO, new Ippassword());
        Ippassword one = this.ippasswordService.getOne(new QueryWrapper<>(ippassword));
        if(one == null || StringUtils.isBlank(one.getId())){
            String s = HttpUtil.get("http://" + ippassword.getHostaddress() + ":10086/health/health");
            Map map = JSONUtil.toBean(s, Map.class);
            if("0".equals(map.get("code").toString())){
                Map<String, Object> map1 = (Map<String, Object>) map.get("data");
                String hostPwd;
                if(StringUtils.isBlank(map1.get("remoteAddress").toString())){
                    hostPwd = map1.get("hostPwd").toString();
                }else {
                    hostPwd = "********";
                }
                one  = new Ippassword(){{
                    setHostaddress(map1.get("hostAddress").toString());
                    setRemoteaddress(map1.get("remoteAddress").toString());
                    setHostpwd(hostPwd);
                }};

            }
        }else {
//            String clientIp = RequestUtil.getClientIp(request);
            if(StringUtils.isBlank(one.getBindaddress())
                    || !ippasswordDTO.getClientIP().equals(one.getBindaddress())){
                one.setHostpwd("********");
            }
            if(StringUtils.isBlank(one.getBindaddress())){
                one.setBindaddress("未绑定");
            }
        }
        return success(one);

    }

    /**
     * 新增数据
     *
     * @param ippassword 实体对象
     * @return 新增结果
     */
    @PostMapping("/insert")
    public R insert(@RequestBody Ippassword ippassword) {
        return success(this.ippasswordService.save(ippassword));
    }

    /**
     * 修改数据
     *
     * @param ippassword 实体对象
     * @return 修改结果
     */
    @PostMapping("/update")
    public R update(@RequestBody Ippassword ippassword) {
        return success(this.ippasswordService.updateById(ippassword));
    }

    @PostMapping("/saveorupdate")
    public R saveorupdate(@RequestBody Ippassword ippassword) {
        Ippassword hostaddress = this.ippasswordService.getOne(new QueryWrapper<Ippassword>()
                .eq("hostaddress", ippassword.getHostaddress()));
        ippassword.setStatus(0);
        if(hostaddress==null || StringUtils.isBlank(hostaddress.getId())){
            return success(this.ippasswordService.save(ippassword));

        }else {
            ippassword.setId(hostaddress.getId());
            ippassword.setBindaddress(hostaddress.getBindaddress());
            ippassword.setBindTime(hostaddress.getBindTime());
            return success(this.ippasswordService.updateById(ippassword));
        }
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @PostMapping("/delete")
    public R delete(@RequestParam("id") String id) {
        return success(this.ippasswordService.removeById(id));
    }

    @PostMapping("/bindIp")
    public R bindIp(@RequestBody IppasswordDTO ippasswordDTO,HttpServletRequest request) {
        Ippassword one = this.ippasswordService.getOne(new QueryWrapper<>(new Ippassword(){{
            setHostaddress(ippasswordDTO.getHostaddress());
        }}));
        if(one == null || StringUtils.isBlank(one.getId())){
            return failed("该服务器不存在，无法绑定！");
        }
        if(StringUtils.isNotBlank(one.getBindaddress())){
            return failed("该服务器已绑定，无法再次绑定！");
        }
//        String clientIp = RequestUtil.getClientIp(request);
        Ippassword one1 = this.ippasswordService.getOne(new QueryWrapper<>(new Ippassword(){{
            setBindaddress(ippasswordDTO.getClientIP());
        }}));
        if(one1 != null){
            return failed("已绑定其他服务器，无法绑定！");
        }
        ippasswordDTO.setHostpwd(one.getHostpwd());
        ippasswordDTO.setBindaddress(ippasswordDTO.getClientIP());
        ippasswordDTO.setId(one.getId());
        ippasswordDTO.setBindTime(new Date());
        Ippassword ippassword = DataConvertUtils.convertDO2DTO(ippasswordDTO, new Ippassword());
        boolean result = this.ippasswordService.updateById(ippassword);
        if(result){
            this.ippasswordService.task(ippassword);
            R apiResult = new R();
            apiResult.setCode(0L);
            apiResult.setData(true);
            apiResult.setMsg("请在60s内完成服务器的登录");
            return apiResult;
        }else {
            return success(result);

        }
    }
    @PostMapping("/unbindIp")
    public R unbindIp(@RequestBody IppasswordDTO ippasswordDTO, HttpServletRequest request) {
        Ippassword one = this.ippasswordService.getOne(new QueryWrapper<>(new Ippassword(){{
            setHostaddress(ippasswordDTO.getHostaddress());
        }}));
        if(one == null || StringUtils.isBlank(one.getId())){
            return failed("该服务器不存在，无法绑定！");
        }
        if(StringUtils.isBlank(one.getBindaddress())){
            return failed("该服务器未绑定，无法再次解绑！");
        }
//        String clientIp = RequestUtil.getClientIp(request);
        if(!ippasswordDTO.getClientIP().equals(one.getBindaddress())){
            return failed("该IP无法解除绑定！");
        }
        String s = HttpUtil.get("http://" + ippasswordDTO.getHostaddress() + ":10086/health/pwd");
        Map map = JSONUtil.toBean(s, Map.class);
        String hostPwd = null;
        if("0".equals(map.get("code").toString())) {
            Map<String, Object> map1 = (Map<String, Object>) map.get("data");
            hostPwd = map1.get("hostPwd").toString();
        }
        ippasswordDTO.setBindaddress(null);
        ippasswordDTO.setId(one.getId());
        ippasswordDTO.setHostpwd(hostPwd);
        ippasswordDTO.setBindTime(null);
        Ippassword ippassword = DataConvertUtils.convertDO2DTO(ippasswordDTO, new Ippassword());
        return success(this.ippasswordService.updateById(ippassword));
    }

    /**
     * 获取客户端IP
     * @param request
     * @return
     */
    @PostMapping("/getClientIP")
    public R getClientIP(HttpServletRequest request) {
        return success(RequestUtil.getClientIp(request));
    }

}

